﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Transforms.Core
{
    internal class SourceNotFoundException : Exception { };

    public class PathSourceFactory
    {
        public class PairNameItem
        {
            public string Name { get; set; }
            public IDataSource Item { get; set; }
        }

        public static IEnumerable<PairNameItem> GetFiles(string path, Func<string, bool> filter)
        {
            if (Directory.Exists(path))
            {
                // TODO: Test performance
                var query = from file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                            where (filter == null || filter(file))
                            select new PairNameItem
                            {
                                Name = file.Remove(0, FileUtils.GetFileDirectoryPath(path).Length),
                                Item = new FileSourceItem(file)
                            };

                foreach (var pair in query)
                    yield return pair;
            }
            else
            {
                if (!File.Exists(path))
                    throw new SourceNotFoundException();

                yield return new PairNameItem
                {
                    Name = Path.GetFileName(path),
                    Item = new FileSourceItem(path)
                };
            }
        }
    }
}
